<?php
declare(strict_types=1);



/**
 * Class AbstractTable
 * @package txz\common\third_lib\model\lib
 */
abstract class AbstractTable
{
    /**
     * @param $dbName
     * @param $tableName
     * @param $pre
     * @param $suffix
     * @return mixed
     */
    abstract function process($dbName, $tableName, $pre, $suffix);

    /**
     * @return mixed
     */
    abstract function getCon();

    /**
     * @param $key
     * @return mixed
     */
    abstract function buildConnection($key);

    /**
     * @param $dbName
     * @param $tableName
     * @param string $pre
     * @param string $suffix
     * @param bool $connect
     */
    public function init($dbName, $tableName, $pre = '', $suffix = '', $connect = true)
    {
        $namespace_arr = explode('\\', $dbName);
        $dbName = $namespace_arr[count($namespace_arr) - 1];

        $class_arr = explode('\\', $tableName);
        $tableName = $class_arr[count($class_arr) - 1];

        $tableName = lcfirst($tableName);
        $tmp = '';
        $strLen = strlen($tableName);
        for ($i = 0; $i < $strLen; $i++) {
            $code = ord($tableName[$i]);
            if ($code > 64 && $code < 91) {
                $tmp .= '_' . chr($code + 32);
            } else {
                $tmp .= $tableName[$i];
            }
        }


        $this->process($dbName, $tmp, $pre, $suffix);

        if($connect){
            $this->con = DbMgr::get($this);
        }

    }

    /**
     * @param $key
     * @return mixed
     */
    public function getConnection($key)
    {
        return $this->buildConnection($key);
    }

    protected $con = null;
    private $dbName = null;
    private $tableName = null;
    private $pre = null;
    private $suffix = null;

    /**
     * @return null
     */
    public function getDbName()
    {
        return $this->dbName;
    }

    /**
     * @param null $dbName
     */
    public function setDbName($dbName)
    {
        $this->dbName = $dbName;
    }

    /**
     * @return null
     */
    public function getTableName()
    {
        return $this->tableName;
    }

    /**
     * @param null $tableName
     */
    public function setTableName($tableName)
    {
        $this->tableName = $tableName;
    }

    /**
     * @return null
     */
    public function getPre()
    {
        return $this->pre;
    }

    /**
     * @param null $pre
     */
    public function setPre($pre)
    {
        $this->pre = $pre;
    }

    /**
     * @return null
     */
    public function getSuffix()
    {
        return $this->suffix;
    }

    /**
     * @param null $suffix
     */
    public function setSuffix($suffix)
    {
        $this->suffix = $suffix;
    }
}

